<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form v-if="key == 1" size="small" :model="pageData" layout="inline">
            <a-form-item label="织布单号">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" @search="handleSearch"
                                  v-model="pageData.lingliaodanhao" :filter-option="false" allow-search allow-clear
                                  @focus="focusSel">
                                  <a-option v-for="item in pageData.lingliaodanhaos">{{ item.planOrderCode }}</a-option>
                              </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.zhibudanhao" @press-enter="huiche" />
            </a-form-item>
            <a-form-item label="原料编号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.yuanliaobianhao" @press-enter="huiche" />
            </a-form-item>
            <a-form-item label="原料名称">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.yuanliaomingc" @press-enter="huiche" />
            </a-form-item>
            <a-form-item label="日期">
              <a-range-picker  popup-container="html"  :style="{ width: '250px' }" class="bacClass" @select="onSelect" @press-enter="huiche"
                @clear="onClear" />
            </a-form-item>
            <a-form-item label="状态">
              <a-select popup-container="html"  :style="{ width: '200px' }" class="bacClass" v-model="pageData.statesState">
                <a-option :value="0">未处理</a-option>
                <a-option :value="1">已处理</a-option>
                <a-option :value="2">全部</a-option>
              </a-select>
            </a-form-item>
          </a-form>
          <a-form v-if="key == 2" size="small" :model="pageData" layout="inline">
            <a-form-item label="领料单号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.lingliaodanhao" @press-enter="huiche2" />
            </a-form-item>
            <a-form-item label="原料编号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.yuanliaobianhao2" @press-enter="huiche2" />
            </a-form-item>
            <a-form-item label="原料名称">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.yuanliaomingc2" @press-enter="huiche2" />
            </a-form-item>
            <a-form-item label="开单日期">
              <a-range-picker  popup-container="html"  :style="{ width: '250px' }" class="bacClass" @select="onSelect" @press-enter="huiche2"
                @clear="onClear" />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <!-- @del="deleteHandler" -->
          <!-- @audit="audits" -->
          <!-- @counter="counters" -->
          <!-- 创建领料单 -->
          <Toolbar v-if="key == 1" :items="[`${permissionStore.hasPermisson('xqdcjlld.xqdcx') ? '查询' : ''}`,
          `${permissionStore.hasPermisson('xqdcjlld.xdqhz') ? '单据汇总' : ''}`]" @select="selectCx"
            @xqHuiz="chuangjianlinliaodans">
          </Toolbar>
          <Toolbar v-if="key == 2" :items="[`${permissionStore.hasPermisson('xqdcjlld.lldcx') ? '查询' : ''}`]"
            @select="selectCx">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" :justify="true" :default-active-key="2" @change="changeKey">
        <!-- <a-tab-pane title="单据明细" :key="1"> -->
        <!-- <a-table style="height: 100%" size="mini" :scrollbar="true" sticky-header stripe :columns="tableColumns"
            :loading="table.tableLoading" :data="table.dataList" :pagination="false" :bordered="{ cell: true }">
          </a-table> -->
        <!-- <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady"
            style="height: 100%" :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList"
            :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
        </a-tab-pane> -->
        <a-tab-pane title="单据汇总" :key="2">
          <!-- <a-table style="height: 100%" size="mini" :scrollbar="true" sticky-header stripe :columns="tableColumns2"
            :loading="table.tableLoading" :data="datas" :pagination="false" rowKey="id" :bordered="{ cell: true }">
            <template #auditState="{ record }">
              <a-button v-if="record.auditState == 4" disabled size="mini" type="primary"
                status="success">已&nbsp;&nbsp;拆&nbsp;&nbsp;纱</a-button>
              <a-button v-if="record.auditState == 3" disabled size="mini" type="primary"
                status="success">已&nbsp;&nbsp;领&nbsp;&nbsp;料</a-button>
              <a-button v-if="record.auditState == 2" disabled size="mini" type="primary"
                status="danger">&nbsp;&nbsp;驳&nbsp;&nbsp;&nbsp;&nbsp;回&nbsp;&nbsp;</a-button>
              <a-button v-if="record.auditState == 1" disabled size="mini" type="primary" status="success">审核通过</a-button>
              <a-button v-if="record.auditState == 0" disabled size="mini" type="primary"
                status="warning">未&nbsp;&nbsp;审&nbsp;&nbsp;核</a-button>
            </template>
            <template #cz="{ record }">
              <a-button type="primary" size="mini" status="success" @click="xiugais(record)">修改</a-button>
            </template>
          </a-table> -->
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady2"
            style="height: 100%" :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="datas" :columnDefs="tc2"
            :localeText="localeText1"></AgGridVuesCopys>
        </a-tab-pane>
      </a-tabs>
    </template>
    <paginationCopys :page-size-options="pagingList1" :total="pagination.total" show-total show-jumper show-page-size
      @change="PageSize" v-if="key == 1" @page-size-change="change1" style="justify-content: center" />
    <paginationCopys :page-size-options="pagingList1" :total="pagination1.total" show-total show-jumper show-page-size
      @change="PageSize1" v-if="key == 2" @page-size-change="change2" style="justify-content: center" />
    <a-drawer :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd1"
      unmountOnClose @ok="sideOk" @cancel="pageData.showAdd1 = false" cancel-text='关闭' ok-text='保存'>
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="objectOP">
          <a-form-item label-col-flex="80px" label="重量">
            <a-input-number class="bacClass" v-model="objectOP.needWeight" />
          </a-form-item>
          <a-form-item label-col-flex="80px" label="件数">
            <a-input-number class="bacClass" v-model="objectOP.pieceCount" />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" :width="800"
      popup-container=".arco-tabs-content" height="100%" :visible="showAdd" placement="bottom" unmountOnClose
      @cancel="sideNo1" @ok="sideOks" :closable="false">
      <template #title>
        {{ llTitel }}
      </template>
      <div style="width: 1500px; overflow: auto" class="scrollbar">
        <el-scrollbar>
          <a-form ref="formRef" :model="dataForms" size="mini" layout="inline">
            <a-form-item :style="{ width: '350px' }" label-col-flex="100px" label="领料单号">
              <a-input v-model="dataForms.planMaterialCode" disabled :style="{ width: '280px' }" />
            </a-form-item>
            <a-form-item :style="{ width: '350px' }" label-col-flex="100px" label="开单日期">
              <a-input v-model="dataForms.createTime" disabled :style="{ width: '280px' }" />
            </a-form-item>
            <a-form-item :style="{ width: '350px' }" label-col-flex="100px" label="开单人员">
              <a-input v-model="dataForms.tabulationPerson" disabled :style="{ width: '280px' }" />
            </a-form-item>
            <a-form-item :style="{ width: '350px' }" label-col-flex="100px" label="客户名称">
              <a-input v-model="dataForm.customName" disabled :style="{ width: '280px' }" />
            </a-form-item>
            <a-form-item :style="{ width: '350px' }" label-col-flex="100px" label="业务部门" field="planMaterialdepartment"
              :rules="[{ required: true, message: '部门必填' }]" :validate-trigger="['change', 'blur']">
              <a-cascader :style="{ width: '280px' }" class="bacClass" v-model="dataForms.planMaterialdepartment"
                :options="firmLists" @focus="getFirmGroup"
                popup-container="html"
                @change="getFirmGroupsz($event, dataForms.planMaterialdepartment)" allow-clear ref="casOb"
                :title="pageData.title"   />
            </a-form-item>
            <a-form-item :style="{ width: '350px' }" label-col-flex="100px" label="业务员" field="planMaterialPerson"
              :rules="[{ required: true, message: '部门必填' }]" :validate-trigger="['change', 'blur']">
              <a-select popup-container="html"  :style="{ width: '280px' }" class="bacClass" v-model="dataForms.planMaterialPerson"
                @click="getYgName" :filter-option="false" allow-search allow-clear>
                <a-option v-for="(item, index) in ygNameList" :key="index">
                  {{ item['name'] }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item :style="{ width: '1580px' }" label-col-flex="100px" label="备注">
              <!-- <a-input class="bacClass" v-model="dataForms.remark" :style="{ width: '280px' }" /> -->
              <a-textarea class="bacClass" placeholder="" v-model="dataForms.remark" :max-length="400" allow-clear
                show-word-limit :style="{ width: '1357px' }" />
            </a-form-item>
          </a-form>
          <a-table size="mini" :scrollbar="true" sticky-header stripe :columns="tableColumns1" :data="dataList"
            :pagination="false" :bordered="{ cell: true }">
            <template #planMaterialWeight="{ record }">
              <a-input-number :precision="2" v-model="record['planMaterialWeight']"></a-input-number>
            </template>
            <template #needWeight="{ record }">
              <a-input-number class="bacClass" v-model="record['needWeight']"></a-input-number>
            </template>
            <template #firmId="{ record }">
              <a-input v-model="record['outSouringCompany']" disabled></a-input>
            </template>
            <template #warehouseName="{ record }">
              <a-input v-model="record['warehouseName']" disabled></a-input>
            </template>
            <template #cz="{ record }">
              <a-space>
                <a-button type="primary" size="mini" status="success" @click="kucun(record)">库存</a-button>
                <a-button size="mini" status="success" @click="xingqs(record)">详情</a-button>
              </a-space>
            </template>
          </a-table>
        </el-scrollbar>
      </div>
    </a-drawer>
    <a-modal :width="500" v-model:visible="visible" :on-before-ok="handleOk" @cancel="handleCancel">
      <template #title>
        需求单汇总
      </template>
      <a-form ref="formRef2" layout="inline" :model="searchData" size="mini">
        <CorporateSectorCascader ref="corPor" :configCascader="configCascader" @changeCascader="changeCascader" />
        <a-form-item label="发货仓库" :rules="[{ required: true, message: '仓库必填' }]" field="warehouseId">
          <a-select popup-container="html"  class="bacClass" :style="{ width: '15rem' }" v-model="searchData.warehouseId" allow-clear>
            <a-option v-for="item in fhWhList" :value="item.id">
              {{ item.warehouseName }}
            </a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </pageTabelLayout>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from "@/hooks/useEventBus";
import { tableColumns1 as tableColumns } from '../useTableList'
import { Message, Modal } from '@arco-design/web-vue'
import { post, get } from '@/api/http'
import { Key } from '@element-plus/icons-vue'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import WHService from "@/service/wh"

import { localeText } from '@/api/aggridZw'
import usePermission from '@/store/modules/permission'
import { pagingList } from '@/api/paging'
import { slicing } from '@/utils/caseFrimAndSecRig'
const permissionStore = usePermission()
const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: true,
  // flex: 1
}

const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}

const gridOption2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
}


let tc: any[] = tableColumns.map((o: any) => {

  let obj = {
    headerName: o.title,
    field: o.key,
    pinned: o['fixed']
  }
  if (o.slotName === 'disposeState') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['lockPosition'] = 'left'
    obj['width'] = 120,
      obj['cellRenderer'] = {
        template: `
          <a-space>
              <el-tag type="success" v-if="submitState == 0">未处理</el-tag>
              <el-tag type="warning"  v-if="submitState == 1">已处理</el-tag>
          </a-space>
          `,
        setup(props: any) {
          return {
            submitState: props.params.data.disposeState,
          }
        }
      }
  }
  if (o.slotName === 'cz') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['lockPosition'] = 'left'
    obj['width'] = 120,
      obj['cellRenderer'] = {
        template: `
        <el-button style="color:#165dff;" @click="a" class="gesture" link>修改</el-button>
          `,
        setup(props: any) {
          const a = () => {
            editHandler(props.params.data)
          }
          return {
            a
          }
        }
      }
  }

  return obj
})



const dataForms: any = reactive({})
let dataForm: any = reactive({
  orderWeight: 0,
  price: 0,
  amount: 0,
  pieceNum: 0,
  pieceWeight: 0,
  businessDepartmentId: '',
  customName: ''
})
onMounted(() => {
  doRefreshs()
});
const dataList: any = ref([])
const formRef = ref()
const key = ref(2)
const changeKey = (keys: any) => {
  key.value = keys
}
const showAdd = ref(false)
const llTitel = ref()

const sideNo1 = () => {
  if (llTitel.value != '修改领料单') {
    clearInterval(isS)
    post({
      url: 'planSingle/planMaterial/upRedis',
    })
  }
  for (let item in dataForms) {
    dataForms[item] = ''
  }
  showAdd.value = false
}

const sideOks = () => {
  // formRef.value?.validate().then((err) => {
  //               if (!err) {
  formRef.value.validate().then((err: any) => {
    if (!err) {
      try {
        for (let i = 0; i < dataList.value.length; i++) {
          if (
            dataList.value[i]['needWeight'].length == 0 ||
            dataList.value[i]['needWeight'] == undefined ||
            dataList.value[i]['needWeight'] == null
          ) {
            Message.error('请输入领料重量')
            return
          }
        }
        if (llTitel.value != '修改领料单') {
          post({
            url: 'planSingle/planMaterial/insert',
            data: {
              ...dataForms,
              companyId: dataForms.planMaterialdepartment,
              idList: dataList.value[0].idList,
              planMaterData: dataList.value,
              warehouseId: dataList.value[0].warehouseId,
              warehouseName: dataList.value[0].warehouseName
            },
          }).then((res: any) => {
            if (res.code == 200) {
              for (let item in dataForms) {
                dataForms[item] = ''
              }
              Message.success(res.message)
              doRefresh()
              clearInterval(isS)
              post({
                url: 'planSingle/planMaterial/upRedis',
              })
              showAdd.value = false
            } else {
              Message.error(res.message)
            }
          })
        } else {
          post({
            url: 'planSingle/planMaterial/update',
            data: {
              ...dataForms,
              planMaterData: dataList.value,
            },
          }).then((res: any) => {
            if (res.code == 200) {
              for (let item in dataForms) {
                dataForms[item] = ''
              }
              Message.success(res.message)
              doRefresh()
              showAdd.value = false
            } else {
              Message.error(res.message)
            }
          })
        }
      } catch (error) {
        Message.error('请输入领料数量')
        return
      }
    }
  })
}

const pagination = usePagination(doRefresh)
const pagination1 = usePagination(doRefreshs)
const table = useTable()

let selectedRowKeys = ref([])

function PageSize(val: any) {
  pagination.page = val
  doRefresh()

}

function change1(val: any) {
  pagination.pageSize = val
  doRefresh()

}
function PageSize1(val: any) {
  pagination1.page = val

  doRefreshs()

}

function change2(val: any) {
  pagination1.pageSize = val

  doRefreshs()

}

async function doRefresh() {
  if (pageData.dropDownDataqszs != undefined) {
    var startDate = pageData.dropDownDataqszs.startDate
    var endDate = pageData.dropDownDataqszs.endDate
    let data1 = startDate
    let data2 = endDate
    var formatDate1 = new Date(startDate)
    var formatDate2 = new Date(endDate)
    if (formatDate1 > formatDate2) {
      startDate = data2 ? data2 + ' 00:00:00' : ''
      endDate = data1 ? data1 + ' 23:59:59' : ''
    } else {
      startDate = data1 ? data1 + ' 00:00:00' : ''
      endDate = data2 ? data2 + ' 23:59:59' : ''
    }
  } else {
    (startDate = ''), (endDate = '')
  }
  const res = await post({
    url: 'planSingle/planNeed/getPage',
    data: {
      page: pagination.page,
      size: pagination.pageSize,
      deleteState: 0,
      auditState: 0,
      startDate,
      endDate,
      planOrderCode: pageData.zhibudanhao,
      rawmaterialCode: pageData.yuanliaobianhao,
      rawmaterialName: pageData.yuanliaomingc,
      disposeState: pageData.statesState == 2 ? undefined : pageData.statesState,
    },
  })
  if (res.code == 200) {
    table.handleSuccess(res.data.list)
    gridOption.value.setRowData(res.data.list)
    pagination.setTotalSize(res.data.total)
  }
}

const selectCx = () => {
  if (key.value == 1) {
    doRefresh()
  } else {
    doRefreshs()
  }
}
let isS: any
// const chuangjianlinliaodans = async () => {
//   if (selectedRowKeys.value.length == 0) {
//     Message.error('请勾选数据')
//     return false
//   }
//   let isDatasArray: any = []
//   selectedRowKeys.value.forEach((o: any) => {
//     table.dataList.forEach((v: any) => {
//       if (o == v.id) {
//         isDatasArray.push(v)
//       }
//     })
//   })
//   for (var i = 0; i < isDatasArray.length; i++) {
//     for (var j = 1; j < isDatasArray.length; j++) {
//       if (isDatasArray[i].planOrderCode != isDatasArray[j].planOrderCode) {
//         Message.error('请勾选相同领料单')
//         return false
//       }
//       if (isDatasArray[i].machineCode != isDatasArray[j].machineCode) {
//         Message.error('请勾选相同机台号')
//         return false
//       }
//     }
//   }
//   const res: any = await post({
//     url: 'planSingle/planMaterial/redisOut',
//     data: selectedRowKeys.value,
//   })
//   if (res.code == 200) {
//     let isData: any = []
//     selectedRowKeys.value.forEach((o: any) => {
//       table.dataList.forEach((v: any) => {
//         if (o == v.id) {
//           isData.push(v)
//         }
//       })
//     })
//     dataList.value = isData
//     post({
//       url: 'planSingle/planMaterial/getAutomaticInfo',
//     }).then((resz: any) => {
//       if (resz.code == 200) {
//         dataForms.planMaterialCode = resz.data.planMaterialCode
//         dataForms.createTime = resz.data.planDate
//         dataForms.tabulationPerson = resz.data.tabulationPerson
//         llTitel.value = '创建领料单'
//         showAdd.value = true
//       } else {
//         Message.error(resz.message)
//       }
//     })
//   } else {
//     Message.error(res.message)
//   }
//   isS = setInterval(() => {
//     post({
//       url: 'planSingle/planMaterial/redisOut',
//       data: selectedRowKeys.value,
//     })
//   }, 290000)
// }

const chuangjianlinliaodans = () => {
  // Modal.confirm({
  //   title: '系统提示',
  //   content: '是否汇总',
  //   onOk() {
  //     post({
  //       url: "planSingle/planMaterial/saveTotalOrder",
  //     }).then((res: any) => {
  //       if (res.code === 200) {
  //         doRefresh()
  //         doRefreshs()
  //         Message.success('汇总成功')
  //         selectedRowKeys.value = []
  //       } else {
  //         Message.error(res.message)
  //       }
  //     })
  //   }
  // })
  visible.value = true
}

const tableColumns1: any = [
  {
    title: '织布单号',
    key: 'planOrderCode',
    dataIndex: 'planOrderCode',
    width: 150,
  },
  {
    title: '需求单号',
    key: 'planNeedCode',
    dataIndex: 'planNeedCode',
    width: 150,
  },
  {
    title: '机台号',
    key: 'machineCode',
    dataIndex: 'machineCode',
    width: 150,
  },
  {
    title: '色号',
    key: 'colorCode',
    dataIndex: 'colorCode',
    width: 150,
  },
  {
    title: '色称',
    key: 'colorName',
    dataIndex: 'colorName',
    width: 150,
  },
  // {
  //   title: '楼层',
  //   key: 'storey',
  //   dataIndex: 'storey',
  //   width: 150,
  // },
  // {
  //   title: '坯布编号',
  //   key: 'greyCode',
  //   dataIndex: 'greyCode',
  //   width: 200,
  // },
  // {
  //   title: '坯布名称',
  //   key: 'greyName',
  //   dataIndex: 'greyName',
  //   width: 450,
  // },
  {
    title: '原料编号',
    key: 'rawmaterialCode',
    dataIndex: 'rawmaterialCode',
    width: 150,
  },
  {
    title: '原料名称',
    key: 'rawmaterialName',
    dataIndex: 'rawmaterialName',
    width: 150,
  },
  {
    title: '纱牌',
    key: 'brandName',
    dataIndex: 'brandName',
    width: 150,
  },
  {
    title: '批次',
    key: 'yarnBatch',
    dataIndex: 'yarnBatch',
    width: 150,
  },
  {
    title: "领料重量",
    key: "needWeight",
    dataIndex: "needWeight",
    slotName: 'needWeight',
    width: 150,
  },
  {
    title: "整件件数",
    key: "needPieceNum",
    dataIndex: "needPieceNum",
    width: 150,
  },
  {
    title: "整件件重",
    key: "pieceWeight",
    dataIndex: "pieceWeight",
    width: 150,
  },
  // {
  //   title: '公司',
  //   key: 'firmId',
  //   dataIndex: 'firmId',
  //   slotName: 'firmId',
  //   width: 250,
  // },
  // {
  //   title: '仓库',
  //   key: 'warehouseName',
  //   dataIndex: 'warehouseName',
  //   slotName: 'warehouseName',
  //   width: 250,
  // },

  // {
  //     title: "库存整件/件数",
  //     key: "stockAllPieceNum",
  //     dataIndex: "stockAllPieceNum",
  //     width: 150,
  // },
  // {
  //     title: "库存整件/件重",
  //     key: "stockAllPieceWeight",
  //     dataIndex: "stockAllPieceWeight",
  //     width: 150,
  // },
  // {
  //     title: "库存散件/件数",
  //     key: "stockAllPieceWeight",
  //     dataIndex: "stockAllPieceWeight",
  //     width: 150,
  // },
  // {
  //     title: "库存散件/散重",
  //     key: "stockAllPieceWeight",
  //     dataIndex: "stockAllPieceWeight",
  //     width: 150,
  // },
  {
    title: '计划重量',
    key: 'planNeedWeight',
    dataIndex: 'planNeedWeight',
    width: 150,
  },
  {
    title: '单位',
    key: 'unit',
    dataIndex: 'unit',
    width: 150,
  },

]
const gsDatas: any = ref([])
// const getAllActiveCompany = () => {
//   post({
//     url: 'org/firmGroup/getFirmInfoByMap',
//     data: {},
//   }).then((res) => {
//     if (res.code == 200) {
//       gsDatas.value = res.data
//     }
//   })
// }
const warehouseNameArray: any = ref([])
const getAllActiveCompanys = ($event: any, record: any) => {
  record['warehouseName'] = ''
  record['warehouseId'] = ''
  post({
    url: 'wms/warehouse/getWarehouseByPara',
    data: {
      firmId: $event,
      virtuallyState:0
    },
  }).then((res: any) => {
    if (res.code == 200) {
      warehouseNameArray.value = res.data
      // 原纱仓
      warehouseNameArray.value.forEach((item: any) => {
        if (item.warehouseName == '原纱仓') {
          record['warehouseName'] = '原纱仓'
          record['warehouseId'] = item.id
        }
      })
      post({
        url: '',
      })
    }
  })
}
const handleSearchs = (record: any) => {
  if (record['firmId'] == '' || record['firmId'] == undefined || record['firmId'] == null) {
    Message.error('请先选择公司')
    return
  }
}
const visible = ref(false)
const titels: any = ref()
// const handleOk = () => {
//   if (titels.value == '库存') {
//     records['detail'] = data.value.filter((item: any) => {
//       return (
//         item.planMaterialWeight != '' &&
//         item.planMaterialWeight != null &&
//         item.planMaterialWeight != undefined &&
//         item.planMaterialWeight != 0
//       )
//     })
//     if (records['needWeight'].length == 0) {
//       Message.error('请输入领料重量')
//       return false
//     } else {
//       Message.success('成功')
//       data.value = []
//       return true
//     }
//   } else {
//     data.value = []
//     return true
//   }
// }

const handleOk = async () => {
  const err = await formRef2.value.validate()
  if (!err) {
    const res: any = await post({
      url: "planSingle/planMaterial/saveTotalOrder",
      data: {
        warehouseId: searchData.warehouseId
      }
    })
    if (res.code === 200) {
      doRefresh()
      doRefreshs()
      fhWhList.value = []
      searchData.warehouseId = null
      searchData.firmId = null
      corPor.value.resetForm()
      Message.success('汇总成功')
      return true
    } else {
      Message.error(res.message)
      return false
    }
  }
}

const xingqs = (record: any) => {
  titels.value = '库存详情'
  visible.value = true
  data.value = record['detail']
}
const handleCancel = () => {
  fhWhList.value = []
  searchData.warehouseId = null
  searchData.firmId = null
  corPor.value.resetForm()
  visible.value = false
}
const firmNames: any = ref()
const firmIds: any = ref()
const whNames: any = ref()
const pichs: any = ref()
const rawmaterialCodes: any = ref()
const rawmaterialNames: any = ref()
let records: any = {}
const kucun = (record: any) => {
  records = record
  data.value = record['detail']
  titels.value = '库存'
  firmNames.value = record.outSouringCompany
  firmIds.value = record.outSouringCompanyId
  whNames.value = record.warehouseName
  rawmaterialCodes.value = record.rawmaterialCode
  rawmaterialNames.value = record.rawmaterialName
  pichs.value = record.batch
  visible.value = true
}
const total = ref(10)
const page = ref(1)
const size = ref(10)
function PageSizes(val: any) {
  page.value = val
  defuncx()
}
function change1s(val: any) {
  size.value = val
  defuncx()
}
const defuncx = () => {
  post({
    url: 'wms/WarehousetypeFieldvalue/getStockByPage',
    data: {
      page: page.value,
      size: size.value,
      warehouseName: whNames.value,
      warehouseTypeName: '原纱仓',
      firmId: firmIds.value,
      batch: pichs.value,
      rawMaterialCode: rawmaterialCodes.value,
      // "rawMaterialName": rawmaterialNames.value,
      infoType: 0,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      data.value = res.data.list
      total.value = res.data.total
    }
  })
}
const data = ref([])
const columns: any = ref([
  {
    title: '单据编号',
    key: 'orderNo',
    dataIndex: 'orderNo',
    width: 150,
  },
  {
    title: '原料编号',
    key: 'rawMaterialCode',
    dataIndex: 'rawMaterialCode',
    width: 150,
  },
  {
    title: '原料名称',
    key: 'rawMaterialName',
    dataIndex: 'rawMaterialName',
    width: 150,
  },
  {
    title: '库存整件/件数',
    key: 'pieceNumber',
    dataIndex: 'pieceNumber',
    width: 150,
  },
  {
    title: '库存整件/件重',
    key: 'pieceWeight',
    dataIndex: 'pieceWeight',
    width: 150,
  },
  {
    title: '库存散件/件数',
    key: 'bulkNumber',
    dataIndex: 'bulkNumber',
    width: 150,
  },
  {
    title: '库存散件/散重',
    key: 'bulkWeight',
    dataIndex: 'bulkWeight',
    width: 150,
  },
  {
    title: '总数量',
    key: 'totalNum',
    dataIndex: 'totalNum',
    width: 150,
  },
  {
    title: '领料重量',
    key: 'planMaterialWeight',
    dataIndex: 'planMaterialWeight',
    slotName: 'planMaterialWeight',
    width: 150,
    fixed: 'right',
  },
])
const tableColumns2: any = ref([
  {
    title: '领料单号',
    key: 'planMaterialCode',
    dataIndex: 'planMaterialCode',
    width: 150,
  },
  {
    title: '客户名称',
    key: 'customName',
    dataIndex: 'customName',
    width: 150,
  },
  {
    title: '开单日期',
    key: 'createTime',
    dataIndex: 'createTime',
    width: 200,
  },
  // {
  //   title: '计划单号',
  //   key: 'planOrderCode',
  //   dataIndex: 'planOrderCode',
  //   width: 150,
  // },
  // {
  //   title: '机台号',
  //   key: 'machineCode',
  //   dataIndex: 'machineCode',
  //   width: 150,
  // },
  {
    title: '原料编号',
    key: 'rawMaterialCode',
    dataIndex: 'rawMaterialCode',
    width: 150,
  },
  {
    title: '原料名称',
    key: 'rawMaterialName',
    dataIndex: 'rawMaterialName',
    width: 300,
  },
  {
    title: '纱牌',
    key: 'brandName',
    dataIndex: 'brandName',
    width: 150,
  },
  {
    title: '纱批',
    key: 'yarnBatch',
    dataIndex: 'yarnBatch',
    width: 150,
  },
  {
    title: '色号',
    key: 'colorCode',
    dataIndex: 'colorCode',
    width: 150,
  },
  {
    title: '色称',
    key: 'colorName',
    dataIndex: 'colorName',
    width: 150,
  },
  {
    title: '可配色称',
    key: "matchColor",
    dataIndex: "matchColor",
    width: 150
  },
  {
    title: '领料重量',
    key: 'planMaterialWeight',
    dataIndex: 'planMaterialWeight',
    width: 150,
    fixed: 'right'
  },
  {
    title: "整件个数",
    key: "pieceCount",
    dataIndex: "pieceCount",
    width: 150,
  },
  {
    title: '库存整件/件数',
    key: 'pieceNumber',
    dataIndex: 'pieceNumber',
    width: 150,
  },
  {
    title: '库存整件/件重',
    key: 'pieceWeight',
    dataIndex: 'pieceWeight',
    width: 150,
  },
  {
    title: '库存散件/件数',
    key: 'bulkNumber',
    dataIndex: 'bulkNumber',
    width: 150,
  },
  {
    title: '库存散件/散重',
    key: 'bulkWeight',
    dataIndex: 'bulkWeight',
    width: 150,
  },
  {
    title: '库存总数量',
    key: 'weightTotal',
    dataIndex: 'weightTotal',
    width: 150,
  },
  {
    title: "单位",
    key: "unit",
    dataIndex: "unit",
    width: 150,
  },
  {
    title: '等级',
    key: "level",
    dataIndex: "level",
    width: 150
  },
  {
    title: '审核状态',
    key: 'auditState',
    dataIndex: 'auditState',
    slotName: 'auditState',
    width: 120,
    fixed: 'right',
  },
  {
    title: '是否加急',
    key: 'urgentState',
    dataIndex: 'urgentState',
    slotName: 'urgentState',
    width: 120,
    fixed: 'right',
  },
  {
    title: '加急件数',
    key: 'urgentCount',
    dataIndex: 'urgentCount',
    slotName: 'urgentCount',
    width: 50,
    fixed: 'right',
  },
])

let tc2: any[] = tableColumns2.value.map((o: any) => {

  let obj = {
    headerName: o.title,
    field: o.key,
    pinned: o['fixed']
  }
  if (o.key == "auditState") {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['cellRenderer'] = {
      template: `
            <a-button v-if="b == 4" disabled size="mini" type="primary"
                status="success">已&nbsp;&nbsp;拆&nbsp;&nbsp;纱</a-button>
              <a-button v-if="b == 3" disabled size="mini" type="primary"
                status="success">已&nbsp;&nbsp;领&nbsp;&nbsp;料</a-button>
              <a-button v-if="b == 2" disabled size="mini" type="primary"
                status="danger">&nbsp;&nbsp;驳&nbsp;&nbsp;&nbsp;&nbsp;回&nbsp;&nbsp;</a-button>
              <a-button v-if="b == 1" disabled size="mini" type="primary" status="success">审核通过</a-button>
              <a-button v-if="b == 0" disabled size="mini" type="primary"
                status="warning">未&nbsp;&nbsp;审&nbsp;&nbsp;核</a-button>
            `,
      setup(props: any) {
        return {
          b: props.params.data.auditState,

        }
      }
    }

  }
  if (o.key == 'planMaterialWeight') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['width'] = 120
    obj['cellRenderer'] = {
      template: `
      <a-popover title="需求单明细">
              <a-button :style="{ width: '100px' }" type="outline">{{b}}</a-button>
              <template #content>
                <a-table :columns="columns" :data="c" :pagination="false"/>
              </template>
           </a-popover>
            `,
      setup(props: any) {
        const columns = ref([
          {
            title: '需求单号',
            key: 'planNeedCode',
            dataIndex: 'planNeedCode',
            width: 180,
          },
          {
            title: '机台号',
            key: 'machineCode',
            dataIndex: 'machineCode',
            width: 100,
          },
          {
            title: '需求数量',
            key: 'needPieceNum',
            dataIndex: 'needPieceNum',
            width: 100,
          },
          {
            title: '需求重量',
            key: 'needWeight',
            dataIndex: 'needWeight',
            width: 100,
          },
        ])
        return {
          columns,
          b: props.params.data.planMaterialWeight,
          c: props.params.data.needInfoList
        }
      }
    }
  }
  if (o.key == 'urgentState') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['width'] = 120
    obj['cellRenderer'] = {
      template: `
            <a-button v-if="b == 0" status="success" size="mini">正常</a-button>
            <a-button v-if="b == 1" type="primary" status="danger" size="mini">加急</a-button>
            `,
      setup(props: any) {
        return {
          b: props.params.data.urgentState,
        }
      }
    }
  }
  return obj
})

const datas: any = ref([])
async function doRefreshs() {
  if (pageData.dropDownDataqszs2 != undefined) {
    var startDate = pageData.dropDownDataqszs2.startDate
    var endDate = pageData.dropDownDataqszs2.endDate
    let data1 = startDate
    let data2 = endDate
    var formatDate1 = new Date(startDate)
    var formatDate2 = new Date(endDate)
    if (formatDate1 > formatDate2) {
      startDate = data2 ? data2 + ' 00:00:00' : ''
      endDate = data1 ? data1 + ' 23:59:59' : ''
    } else {
      startDate = data1 ? data1 + ' 00:00:00' : ''
      endDate = data2 ? data2 + ' 23:59:59' : ''
    }
  } else {
    ; (startDate = ''), (endDate = '')
  }
  const res = await post({
    url: 'planSingle/planMaterial/getPage',
    data: {
      page: pagination1.page,
      size: pagination1.pageSize,
      deleteState: 0,
      startDate,
      endDate,
      planMaterialCode: pageData.lingliaodanhao,
      rawMaterialCode: pageData.yuanliaobianhao2,
      rawMaterialName: pageData.yuanliaomingc2,
    },
  })
  if (res.code == 200) {
    datas.value = res.data.list
    pagination1.setTotalSize(res.data.total)
  }
}
const xiugais = (record: any) => {
  post({
    url: 'planSingle/planMaterial/update',
    data: record,
  }).then((res: any) => {
    if (res.code == 200) {
      for (let key in record) {
        dataForms[key] = record[key]
      }
      // dataForms.planMaterialCode = res.data.planMaterialCode
      // dataForms.createTime = res.data.createTime
      // dataForms.weaveCode = res.data.weaveCode
      // dataForms.planOrderCode = res.data.planOrderCode
      // dataForms.customName = res.data.customName
      // dataForms.planMaterialdepartment = res.data.planMaterialdepartment
      // dataForms.planMaterialPerson = res.data.planMaterialPerson
      // dataForms.remark = res.data.remark
      // dataForms.id = res.data.id
      // dataList.value = res.data.planMaterData
      // titels.value = '修改库存'
      showAdd.value = true
      llTitel.value = '修改领料单'
    } else {
      Message.error(res.message)
    }
  })
}
//可复制使用
const headerShow = ref(true)

const pageData: any = reactive({
  dropDownDataqszs: {
    startDate: '',
    endDate: '',
    isShow: true,
    title: '',
  },
  statesState: 0,
  showAdd1: false
})
const focusSel = () => {
  if (key.value == 1) {
    mohuchaxs({ planOrderCode: '' }, 1)
  } else {
    mohuchax({ planOrderCode: '' }, 1)
  }
}
const handleSearch = (val: any) => {
  if (key.value == 1) {
    mohuchaxs({ planOrderCode: val }, 1)
  } else {
    mohuchax({ planOrderCode: val }, 1)
  }
}
const focusSel2 = () => {
  if (key.value == 1) {
    mohuchaxs({ rawmaterialCode: '' }, 2)
  } else {
    mohuchax({ rawmaterialCode: '' }, 2)
  }
}
const handleSearch2 = (val: any) => {
  if (key.value == 1) {
    mohuchaxs({ rawmaterialCode: val }, 2)
  } else {
    mohuchax({ rawmaterialCode: val }, 2)
  }
}
const focusSel3 = () => {
  if (key.value == 1) {
    mohuchaxs({ rawmaterialName: '' }, 3)
  } else {
    mohuchax({ rawmaterialName: '' }, 3)
  }
}
const handleSearch3 = (val: any) => {
  if (key.value == 1) {
    mohuchaxs({ rawmaterialName: val }, 3)
  } else {
    mohuchax({ rawmaterialName: val }, 3)
  }
}
async function mohuchax(val: any, state: any) {
  const res = await post({
    url: 'planSingle/planMaterial/getDropValue',
    data: val,
  })
  if (res.code == 200) {
    if (state == 1) {
      pageData.lingliaodanhaos = res.data
    }
    if (state == 2) {
      pageData.yuanliaobianhaos = res.data
    }
    if (state == 3) {
      pageData.yuanliaomingcs = res.data
    }
  }
}
async function mohuchaxs(val: any, state: any) {
  const res = await post({
    url: 'planSingle/planNeed/getDropValue',
    data: val,
  })
  if (res.code == 200) {
    if (state == 1) {
      pageData.lingliaodanhaos = res.data
    }
    if (state == 2) {
      pageData.yuanliaobianhaos = res.data
    }
    if (state == 3) {
      pageData.yuanliaomingcs = res.data
    }
  }
}
const onSelect = (dateString: any) => {
  if (key.value == 1) {
    pageData.dropDownDataqszs = {
      startDate: dateString[0],
      endDate: dateString[1],
    }
  } else {
    pageData.dropDownDataqszs2 = {
      startDate: dateString[0],
      endDate: dateString[1],
    }
  }
}
const onClear = () => {
  if (key.value == 1) {
    pageData.dropDownDataqszs = {}
  } else {
    pageData.dropDownDataqszs2 = {}
  }
}

const huiche = () => {
  doRefresh()
}
const firmLists: any = ref([])
const getFirmGroup = () => {
  post({
    url: 'org/baCompany/getTreeCompanyByUser',
  }).then(({ code, data }) => {
    if (code === 200) {
      firmLists.value = data
    }
  })
}
// const getFirmGroupsz = () => {
//     dataForms.planMaterialPerson = ''
// }
const casOb = ref()
const getFirmGroupsz = (event: any, val: any) => {
  //拿到选中的这个节点数组
  setTimeout(function () {
    pageData.title = slicing(casOb.value.selectViewValue[0]['label'])
  }, 500)
  dataForms.planMaterialPerson = ''
  if (val == '' || val == undefined) {
  } else {
    pageData.isShow = false
  }
}
const ygNameList: any = ref([])
const getYgName = () => {
  post({
    url: '/org/hrEmployee/getList',
    data: {
      company_id: dataForms.planMaterialdepartment,
    },
  }).then((res) => {
    if (res.code == 200) {
      ygNameList.value = res.data
    } else {
      Message.error({
        content: '查询员工名称失败',
        duration: 5000,
      })
    }
  })
}

const huiche2 = () => {
  doRefreshs()
}

const searchData: any = reactive({
  warehouseId: null,
  firmId: null
})

const formRef2: any = ref()

const corPor: any = ref()

const configCascader = ref<{}>({
  corporateWidth: '15rem', //公司宽度
  sectorWidth: '180px', //部门宽度
  corporateRquired: true, //公司是否必填
  sectorRquired: false, //部门是否必填
  size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '发货公司', //公司label
  sectorName: '选择部门', //部门label
  cascaderShow: 'sector', //配置部门不显示
})
const whService = new WHService()
const fhWhList: any = whService.whList
const changeCascader = (data: any) => {
  const { corporateId, sectorId, sectorLabel, corporateLabel } = data
  searchData.warehouseId = ""
  searchData.firmId = corporateId
  whService.getWarhouseListByFirmId(corporateId, '原纱仓')
}

const editHandler = (record: any) => {
  for (var key in record) {
    objectOP[key] = record[key]
  }
  pageData.sideTitle = '修改需求单';
  if (record.disposeState == 0) {
    pageData.showAdd1 = true;
  } else {
    pageData.showAdd1 = false;
  }


}
const objectOP = reactive<{
  needWeight: any,
  pieceCount: any,
}>
  ({
    needWeight: null,
    pieceCount: null,
  });
const sideOk = () => {
  // formRef.value?.validate().then((err) => {
  //   if (!err) {
  if (pageData.sideTitle === "修改需求单") {
    post({
      url: "/planSingle/planNeedDetail/update",
      data: [objectOP],
    }).then((res: any) => {
      if (res.code === 200) {
        formRef.value?.resetFields();
        pageData.showAdd1 = false;

        Message.success({
          content: "修改成功",
          duration: 5000,
        });
        doRefresh();
      } else {
        Message.error({
          content: res.message,
          duration: 5000,
        });
      }

    });
  }
  // });
};
</script>
<style lang="less" scoped>
.bg-container {
  background-color: white;
  padding: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  form {
    width: 50% !important;
  }

  // .my-divisders{
  //     margin: 0;
  //     padding: 0;
  // }
  &>.my-header {
    width: 100%;
    padding: 10px;
    background-color: white;
    padding-top: 0;

    // min-height: 10%;
    &>.my-tool-bar {
      text-align: right;
    }
  }
}

.gang {
  background-color: rgb(240, 242, 245);
  height: 10px;
}

.isCxs {
  margin-left: 600px;
  margin-top: 20px;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}
</style>